import {
  HTTP
} from '../../utils/http'
let http = new HTTP()
import Toast from '@vant/weapp/toast/toast';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    active: 0,
    phoneLoginshow: false,
    phoneCloseIcon: '/images/icon/close.png',
    value: '',
    currentTime: 60,
    timeCount: '',
    // 发送验证码
    sendBtnShow: true,
    phone: '',
    // 用户信息
    userInfo: null,
    // 是否绑定手机号
    isBindPhone: false,
    // 验证码
    verifyCode: '',
    userId: '',
    token: '',
    likeWorkList: [],
    workPageNum: 1,
    workPageSize: 10,
    workTotal: 0,
    openId: '',
    editNameShow: false
  },
  onEditName() {
    this.setData({
      editNameShow: !this.data.editNameShow
    })
  },
  onEditNameSuccess(e) {
    // console.log(e); 
    this.onEditName()
    this.editAccount(this.data.userId, e.detail.value)
  },

  editAccount(id, accountName) {
    http.request({
      url: '/ai/draw/account/update',
      method: "POST", // 'multipart/form-data; boundary=XXX'
      contentType: 'multipart/form-data; boundary=XXX',
      // 这肯定有问题啊
      data: '\r\n--XXX' +
        '\r\nContent-Disposition: form-data; name="id"' +
        '\r\n' +
        '\r\n' + id +
        '\r\n--XXX' +
        '\r\nContent-Disposition: form-data; name="accountName"' +
        '\r\n' +
        '\r\n' + accountName +
        '\r\n--XXX',
      success: (data) => {
        if (data.code == '0') {
          this.getUserDetail(id)
        }
      }
    })
  },
  handleLogin() {
    this.setData({
      show: true
    });
  },

  wxLoginTap() {
    wx.getUserProfile({
      desc: '必须授权才能继续使用', // 必填 声明获取用户个人信息后的用途，后续会展示在弹窗中
      success: (res) => {
        console.log('授权成功', res);
        this.setData({
          userInfo: res.userInfo,
          show: false,
          isBindPhone: true
        })
        wx.login({
          success: res => {
            if (res.code) {
              // 发起网络请求
              http.request({
                url: '/ai/draw/login/account/login/wechat',
                data: {
                  jsCode: res.code
                },
                success: (data) => {
                  console.log('登录成功', data);
                  if (!data.data.token) {
                    this.setData({
                      phoneLoginshow: true,
                      openId: data.data.openId
                    })
                  }
                  wx.setStorage({ //缓存token
                    data: data.data.token,
                    key: 'token'
                  })
                  if (data.data.accountInfo?.id) {
                    wx.setStorage({
                      data: data.data.accountInfo.id,
                      key: 'userId'
                    })
                    wx.reLaunch({
                      url: "/pages/home/home"
                    })
                  }
                }
              })
            } else {
              wx.showToast({
                title: '登录失败',
                duration: 2000,
                icon: 'none'
              })
              console.log('登录失败' + res.errMsg)
            }
          }
        })
      },
      fail: (err) => {
        console.log('授权失败', err);
        wx.showToast({
          title: '授权失败',
          duration: 2000,
          icon: 'none'
        })
      }
    })

  },

  // 发送验证码
  sendCodeTap() {
    var that = this;
    this.countDown(that, 60);
    http.request({
      url: '/ai/draw/login/send/verify/code',
      data: {
        bindPhone: this.data.phone
      },
      success: (data) => {
        if (data.code !== "0") {
          wx.showToast({
            title: data.msg,
            duration: 2000,
            icon: 'none'
          })
        }
      }
    })
  },

  countDown(that, count) {
    if (count == 0) {
      that.setData({
        timeCount: '获取验证码',
        sendBtnShow: true
      })
      return;
    }
    that.setData({
      sendBtnShow: false,
      timeCount: count + '秒后重新发送',
    })
    setTimeout(function () {
      count--;
      that.countDown(that, count);
    }, 1000);
  },

  handlePhoneLoginClose() {
    this.setData({
      phoneLoginshow: false
    });
  },

  handlePhoneLogin() {
    this.setData({
      show: false,
      phoneLoginshow: true
    })
  },

  onClose() {
    this.setData({
      show: false
    });
  },

  loginTap() {
    if (this.data.isBindPhone) {
      http.request({
        url: '/ai/draw/login/account/bind/phone',
        data: {
          bindPhone: this.data.phone,
          openId: this.data.openId,
          verifyCode: this.data.verifyCode
        },
        success: (data) => {
          if (data.code === "0") {
            this.setData({
              userId: data.data.accountInfo.id,
              phoneLoginshow: false,
            })
            Toast.success('绑定成功');
          } else {
            wx.showToast({
              title: data.msg,
              duration: 2000,
              icon: 'none'
            })
          }
        }
      })
    } else {
      http.request({
        url: '/ai/draw/login/account/login/phone',
        data: {
          bindPhone: this.data.phone,
          verifyCode: this.data.verifyCode
        },
        success: (res) => {
          if (res.code === "0") {
            this.setData({
              phoneLoginshow: false,
            })
            wx.setStorage({
              data: res.data.token,
              key: 'token'
            })
            wx.setStorage({
              data: res.data.accountInfo.id,
              key: 'userId'
            })
            wx.reLaunch({
              url: "/pages/home/home"
            })
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2000,
              icon: 'none'
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  workCreationTap() {
    wx.navigateTo({
      url: '/pages/my-create-work/my-create-work?accountId=' + this.data.userId
    })
  },

  workCollectTap() {
    wx.navigateTo({
      url: '/pages/my-collect-work/my-collect-work?accountId=' + this.data.userId
    })
  },

  boxCreationTap() {
    wx.navigateTo({
      url: '/pages/my-create-box/my-create-box?accountId=' + this.data.userId
    })
  },

  boxCollectTap() {
    wx.navigateTo({
      url: '/pages/my-collect-box/my-collect-box?accountId=' + this.data.userId
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.setData({
    //   "active": 0
    // })
    let that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        that.setData({
          token: res.data
        })
        // token不存在
        if (!res.data) {
          that.setData({
            userInfo: null
          })
        }
      }
    })
    wx.getStorage({
      key: 'userId',
      success: function (res) {
        that.setData({
          userId: res.data
        });
        if (res.data) {
          that.getUserDetail(res.data)
          that.getlikeWorkList()
        }
      }
    })
  },

  getUserDetail(userId) {
    http.request({
      url: '/ai/draw/account/get/detail',
      data: {
        id: userId
      },
      success: (data) => {
        if (data.code === "0") {
          if (data.code === "0") {
            this.setData({
              userInfo: data.data
            })
          }
        }
      }
    })
  },

  onChange(event) {
    this.setData({
      active: event.detail.index,
      workPageNum: 1,
      workPageSize: 10,
      likeWorkList: []
    })
    if (event.detail.index === 2 && this.data.userInfo !== null) {
      this.setData({
        "pageNum": 1,
        "pageSize": 10
      })
      this.getlikeWorkList()
    } else {
      this.setData({
        "likeWorkList": []
      })
    }
  },

  getlikeWorkList() {
    http.request({
      url: '/ai/draw/picture/get/account/page',
      method: 'post',
      data: {
        "type": 2,
        "pageNum": this.data.workPageNum,
        "pageSize": this.data.workPageSize,
        "accountId": this.data.userId
      },
      success: (res) => {
        if (res.code === "0") {
          let list = res.data.list
          var arr1 = this.data.likeWorkList;
          var arr2 = list;
          arr1 = arr1.concat(arr2);
          this.setData({
            likeWorkList: arr1,
            workTotal: res.data.total
          })
        }
      }
    })

  },

  toAccountList() {
    const accountId = this.data.userId;
    wx.navigateTo({
      url: '/pages/user-list/user-list?accountId=' + accountId,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      workPageNum: 1,
      workPageSize: 10,
      likeWorkList: []
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.active == 2) {
      if (!(this.data.likeWorkList && this.data.likeWorkList.length > 0)) return
      let currentTotal = this.data.likeWorkList.length;
      if (currentTotal <= this.data.workTotal) {
        var current = this.data.workPageNum * 1 + 1;
        this.setData({
          workPageNum: current
        })
        this.getlikeWorkList();
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})